package com.exception.handler;

import com.exception.CustomException;
import com.exception.CustomTransactionalException;
import com.exception.PageIndexIllegalException;
import com.vo.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Version: V1.0    <br/>
 * Datetime:   2021/12/20 19:51   <br/>
 * Description: 全局异常处理
 *
 * @author chen
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理页码异常
     */
    @ExceptionHandler(PageIndexIllegalException.class)
    public Msg processPageIndexIllegalException(PageIndexIllegalException e) {
        return Msg.error(e.getMessage());
    }


    /**
     * 参数格式错误
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Msg httpMessageNotReadable(HttpMessageNotReadableException e) {
        log.error("错误信息: {}", e.getLocalizedMessage());
        return Msg.code(100, "参数格式错误");
    }

    /**
     * 处理自定义事务异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(CustomTransactionalException.class)
    public Msg customTransactionalException(CustomTransactionalException e) {
        log.error("错误信息:{}", e.getMessage());
        return Msg.error(e.getMessage());
    }

    /**
     * 处理自定义事务异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(CustomException.class)
    public Msg customException(CustomException e) {
        log.error("错误信息:{}", e.getMessage());
        return Msg.error(e.getMessage());
    }

    /**
     * 通用异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Msg exception(Exception e) {
        log.error(e.getMessage());
        return Msg.systemError("系统处理出错," + e.getMessage());
    }
}